/**
 * API模块 - 处理所有与后端API的交互
 * 作者: AI Assistant
 * 功能: 浏览统计、点赞功能等API调用
 */

// API基础配置
const API_BASE_URL = window.location.origin; // 自动获取当前页面的域名
const API_ENDPOINTS = {
    SCAN_INCREMENT: '/profile/scan/increment',
    SCAN_COUNT: '/profile/scan/count',
    FAV_LIKE: '/profile/fav/like',
    FAV_UNLIKE: '/profile/fav/unlike',
    FAV_COUNT: '/profile/fav/count',
    FAV_STATUS: '/profile/fav/status'
};

// 获取设备标识符
function getDeviceId() {
    let deviceId = localStorage.getItem('deviceId');
    if (!deviceId) {
        deviceId = 'web_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
        localStorage.setItem('deviceId', deviceId);
    }
    return deviceId;
}

// 获取用户IP（简化版本）
function getUserIP() {
    return 'web_client';
}

// 通用API请求函数
async function apiRequest(endpoint, method = 'GET', data = null) {
    try {
        const url = API_BASE_URL + endpoint;
        const options = {
            method: method,
            headers: {
                'Content-Type': 'application/json',
            }
        };
        
        if (data && (method === 'POST' || method === 'PUT')) {
            options.body = JSON.stringify(data);
        }
        
        const response = await fetch(url, options);
        const result = await response.json();
        
        if (result.code === 1) {
            return { success: true, data: result.ret, message: result.msg };
        } else {
            return { success: false, error: result.msg || '请求失败' };
        }
    } catch (error) {
        console.error('API请求错误:', error);
        return { success: false, error: '网络请求失败' };
    }
}

// 浏览统计API
const ScanAPI = {
    // 增加浏览计数
    async increment() {
        const data = {
            ip: getUserIP(),
            deviceid: getDeviceId()
        };
        return await apiRequest(API_ENDPOINTS.SCAN_INCREMENT, 'POST', data);
    },
    
    // 获取浏览总数
    async getCount() {
        return await apiRequest(API_ENDPOINTS.SCAN_COUNT);
    }
};

// 点赞功能API
const FavAPI = {
    // 点赞
    async like() {
        const data = {
            ip: getUserIP(),
            deviceid: getDeviceId()
        };
        return await apiRequest(API_ENDPOINTS.FAV_LIKE, 'POST', data);
    },
    
    // 取消点赞
    async unlike() {
        const data = {
            ip: getUserIP(),
            deviceid: getDeviceId()
        };
        return await apiRequest(API_ENDPOINTS.FAV_UNLIKE, 'POST', data);
    },
    
    // 获取点赞总数
    async getCount() {
        return await apiRequest(API_ENDPOINTS.FAV_COUNT);
    },
    
    // 获取用户点赞状态
    async getStatus() {
        const params = new URLSearchParams({
            ip: getUserIP(),
            deviceid: getDeviceId()
        });
        return await apiRequest(API_ENDPOINTS.FAV_STATUS + '?' + params.toString());
    }
};

// 导出API模块
window.ProfileAPI = {
    ScanAPI,
    FavAPI,
    getDeviceId,
    getUserIP
}; 